<template>
  <view class="address-edit f fd-col">
    <nav-bar left-text="编辑联系人地址" :url="'address-management'" />
    <bg-set background="#f2f3f7" />
    <view class="address-edit__edit-part">
      <uni-forms ref="form" :rules="rules" :modelValue="formData">
        <uni-forms-item label="姓名" name="userName" required
          ><uni-easyinput
            v-model="formData.userName"
            :inputBorder="false"
            :clearable="false"
            placeholder="请输入姓名"
        /></uni-forms-item>
        <uni-forms-item label="手机号" name="userPhone" required>
          <uni-easyinput
            v-model="formData.userPhone"
            :inputBorder="false"
            :clearable="false"
            placeholder="请输入手机号"
        /></uni-forms-item>
        <uni-forms-item label="地址" name="userAddress" required>
          <uni-easyinput
            v-model="formData.userAddress"
            :inputBorder="false"
            :clearable="false"
            placeholder="请输入地址"
        /></uni-forms-item>
      </uni-forms>
      <view class="f jc-sb ai-c"
        ><text>请选择收寄类型</text
        ><uni-data-checkbox
          v-model="radioValue"
          :localdata="radioRange"
          @change="radioChange"
          mode="tag"
        ></uni-data-checkbox
      ></view>
    </view>
    <view class="address-edit__confirm-part f jc-c ai-c">
      <van-button
        type="primary"
        :loading="isLoading"
        loading-type="spinner"
        loading-text="提交修改中"
        @click="submit"
        round
        style="width: 80%"
        >确认修改</van-button
      >
    </view>
  </view>
</template>

<script>
import profileAPI from "/api/modules/profile";
import StorageOperation from "/utils/storage";
export default {
  name: "address-edit",
  data() {
    return {
      isLoading: false,
      rules: {
        userName: { rules: [{ required: true, errorMessage: "姓名不能为空" }] },
        userPhone: {
          rules: [
            { required: true, errorMessage: "手机号不能为空" },
            {
              validateFunction: (rule, value, data, callback) => {
                // 异步需要返回 Promise 对象
                return new Promise((resolve, reject) => {
                  const reg = /^1[3|4|5|7|8]\d{9}$/;
                  setTimeout(() => {
                    if (reg.test(value)) {
                      // 通过返回 resolve
                      resolve();
                    } else {
                      // 不通过返回 reject(new Error('错误信息'))
                      reject(new Error("手机号码格式错误!"));
                    }
                  }, 0);
                });
              },
            },
          ],
        },
        userAddress: {
          rules: [{ required: true, errorMessage: "地址不能为空" }],
        },
      },
      formData: {
        userName: "",
        userPhone: "",
        userAddress: "",
      },
      formDataCopy: {},
      radioValue: 0,
      radioRange: [
        { value: 0, text: "收件" },
        { value: 1, text: "寄件" },
      ],
      toastStatus: 0,
      toastMessage: ["修改成功", "修改失败，请稍后重试"],
    };
  },
  onLoad(option) {
    const { userPhone, userName, userAddress, mode } = option;
    this.formData = { userPhone, userName, userAddress };
    this.radioValue = Number(mode);
    this.formDataCopy = Object.assign({}, option);
  },
  methods: {
    submit() {
      this.$refs.form
        .validate()
        .then((res) => {
          this.isLoading = true;
          const { userName: oldUserName, userPhone: oldUserPhone } =
            this.formDataCopy;
          const {
            userName: newUserName,
            userPhone: newUserPhone,
            userAddress: newUserAddress,
          } = res;
          const userName = StorageOperation.getStorageSync("userName").value;
          profileAPI
            .updateAddress({
              newUserName,
              newUserPhone,
              newUserAddress,
              mode: this.radioValue,
              oldUserName,
              oldUserPhone,
              userName,
            })
            .then((response) => {
              console.log(response);
              // 更新formDataCopy
              this.formDataCopy = Object.assign({}, this.formData);
              uni.showToast({
                title: this.toastMessage[this.toastStatus],
                icon: "none",
                duration: 2000,
                position: "top",
              });
            })
            .catch((err) => {
              console.log(err);
              this.toastStatus = 1;
              uni.showToast({
                title: this.toastMessage[this.toastStatus],
                icon: "none",
                duration: 2000,
                position: "top",
              });
            })
            .finally(() => {
              this.isLoading = false;
            });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    radioChange(data) {
      this.radioValue = data.detail.value;
    },
  },
};
</script>
<style lang='scss' scoped>
.address-edit {
  position: relative;
  width: 100%;
  height: 100vh;
  &__edit-part {
    padding: 30rpx;
    width: 100%;
    height: calc(100vh - 44rpx);
    box-sizing: border-box;
    background-color: #fff;
    ::v-deep .uni-forms {
      .uni-forms-item {
        .uni-forms-item__label {
          height: 80rpx;
          .label-text {
            font-size: 30rpx;
          }
        }
        .uni-forms-item__content {
          display: flex;
          align-items: center;
          .uni-easyinput__content {
            border-bottom: 1px solid #ccc;
            .uni-easyinput__content-input {
              font-size: 30rpx;
              .uni-input-placeholder {
                font-size: 30rpx;
              }
            }
          }
        }
      }
    }
    ::v-deep .checklist-group {
      justify-content: flex-end;
      .checklist-box {
        width: 80rpx;
        &:last-child {
          margin-right: 0;
        }
        .checklist-content {
          justify-content: center;
        }
      }
    }
  }
  &__confirm-part {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 160rpx;
    background-color: #fff;
    box-shadow: 0 -2px 4px #eee;
  }
}
</style>